﻿using System;
using System.Data;
using System.Data.Objects;
using System.Linq;

namespace Complaint.Models.Dtos
{
    public partial class ComplaintEntities
    {
        partial void OnContextCreated()
        {
            SavingChanges +=
                OnSavingChanges;
        }

        public void OnSavingChanges(object sender, EventArgs e)
        {
            var changedEntities =
                ObjectStateManager
                .GetObjectStateEntries(EntityState.Added | EntityState.Modified)
                .AsQueryable().Where(o => (o.Entity is IEntity));

            foreach (ObjectStateEntry stateEntryEntity in
                    changedEntities)
            {
                if (!((IEntity)stateEntryEntity.Entity).IsValid)
                    throw new ComplaintDataException(
                        String.Format("{0} is Not Valid", stateEntryEntity.Entity.GetType().Name),
                        ((IEntity)stateEntryEntity.Entity).GetRuleViolations());
            }

        }
    }
}
